package com.xls.commonlibrary.app;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;
import com.github.gzuliyujiang.oaid.DeviceIdentifier;
import com.hjq.toast.Toaster;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.tencent.mmkv.MMKV;
import com.xls.commonlibrary.ad.adn.gm.TTAdManagerHolder;
//import com.xls.commonlibrary.risk.RiskUtil;
import com.xls.commonlibrary.util.ActivityManager;
import com.xls.commonlibrary.util.SystemUtil;
import com.xls.commonlibrary.util.UMUtil;

import java.util.List;

import androidx.multidex.MultiDexApplication;

import static com.xls.commonlibrary.constant.Config.debug;

public class MainApplication extends MultiDexApplication {

    private static final String TAG = "MainApplicationLib";
    private static Context context;


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);

        MainApplication.context = this;

    }

    public static Context getAppContext() {
        return MainApplication.context;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        if (debug) {           // These two lines must be written before init, otherwise these configurations will be invalid in the init process
            ARouter.openLog();     // Print log
            ARouter.openDebug();   // Turn on debugging mode (If you are running in InstantRun mode, you must turn on debug mode! Online version needs to be closed, otherwise there is a security risk)
        }
        ARouter.init(this); // As early as possible, it is recommended to initialize in the Application

//        友盟
        UMUtil.getInstance().preInit(this);
        UMUtil.getInstance().init(this);
        Log.d(TAG, "===========onCreate=============");

        // Gromore init
        TTAdManagerHolder.init(this);

        //TODO OaID
        DeviceIdentifier.register(this);//oaid

        // todo 主进程才初始化 避免重复操作
        if (SystemUtil.isMainProcess(this)) {
            // init db
            // 先不要缓存数据库了，有问题的话
            // ObjectBoxUtil.getInstance().init();

            // test db
            // DBUtil.getInstance().insert();

            // 初始化 Toast 框架
            Toaster.init(this);
            // init logger
            FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder().showThreadInfo(true)  // (Optional) Whether to show thread info or not. Default true
                    .methodCount(3)         // (Optional) How many method line to show. Default 2
                    .methodOffset(7)        // (Optional) Hides internal method calls up to offset. Default 5
                    //.logStrategy(customLog) // (Optional) Changes the log strategy to print out. Default LogCat
//                    .tag("new")   // (Optional) Global tag for every log. Default PRETTY_LOGGER
                    .build();

            Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));

            //如果业务需要多进程访问，那么在初始化的时候加上标志位 MMKV.MULTI_PROCESS_MODE：
            // 优点：不依赖context，任意处可以调用
            // 优点：不依赖context，任意处可以调用
            // 优点：不依赖context，任意处可以调用
            String rootDir = MMKV.initialize(this);
            System.out.println("mmkv root: " + rootDir);

            // 以下添加业务代码


            // old ad sdks dont use any more
//            AdInitUtil.initAds();


//            SigmobInitUtil.initSDK();


            // 连山风控 暂时关闭
//            RiskUtil.getInstance().initRisk(this);


//            RiskAliUtil.getInstance().initAliRisk();
            // test
//            RiskAliUtil.getInstance().reportRisk();

        }

        registerActivityListener();
    }


    private void registerActivityListener() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
                @Override
                public void onActivityCreated(Activity activity, Bundle bundle) {
                    ActivityManager.pushActivity(activity);
                }

                @Override
                public void onActivityStarted(Activity activity) {

                }

                @Override
                public void onActivityResumed(Activity activity) {

                }

                @Override
                public void onActivityPaused(Activity activity) {

                }

                @Override
                public void onActivityStopped(Activity activity) {

                }

                @Override
                public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

                }

                @Override
                public void onActivityDestroyed(Activity activity) {
                    List<Activity> mActivitys = ActivityManager.getmActivitys();
                    if (null == mActivitys || mActivitys.isEmpty()) {
                        return;
                    }
                    if (mActivitys.contains(activity)) {
                        ActivityManager.popActivity(activity);
                    }
                }
            });
        }
    }


}
